<?php
if (!class_exists('PropelGenerator')) {
	/**
	 *  CRUD generator dao class for Propel ORM
	 *	@author Alecsandru Gabriel DINU
	 *  @since Jun 20, 2008
	 */
	class PropelGenerator {

		private $argv;
		private $config;

		public function __construct() {
			ini_set('ze1_compatibility_mode', 'Off');
			ini_set('magic_quotes_gpc', 'Off');
			ini_set('magic_quotes_sybase', 'Off');

			$this->config = AlfaConfiguration::getInstance();
			$root = $this->config->getString('appCoreRootDir');
			
			require_once("src/main/classes/core/log/PhingScreenLogger.php");

			$this->argv[] = "-Dproject=alfa-child";
			$this->argv[] = "-buildfile";
			$this->argv[] = $root . "/src/lib/propel/generator/build.xml";
			$this->argv[] = "-Dusing.propel-gen=true";
			$this->argv[] = "-Dproject.dir=" . $this->config->getString('build/path/schema');
			$this->argv[] = "-logger";
			$this->argv[] = "PhingScreenLogger";
			$this->argv[] = "-verbose";

		}

		/**
		 * Executes a Propel command
		 */
		public function execute($target) {
			$argv = $this->argv;

			if (isset($target) && trim($target) !== '') {
				$argv[] = "-Dtarget=$target";
			}

			require_once 'lib/phing/bin/phing.php';
		}


		/**
		 * This method is used to transform a DB4 Designer
		 * to Propel schema file.
		 * It applies a XSL transformation to DB4 Designer xml. 
		 * 
		 * Db4 Designer was replace by MySQL Workbench which has a 
		 * plugin for exporting Propel schema file.
		 * So, this method is deprecated but I left it here
		 * to serve as an example. 
		 */		
		public function dbd2propel($model, $schema) {
			
			if (isset($model) && trim($model) != '') {
				$dbd2_file = $model;
			} else {
				$dbd2_file = $this->config->getString('build/path/schema') . "/model.xml";	
			}

			if (isset($schema) && trim($schema) != '') {
				$propel_file = $schema;
			} else {
				$propel_file = $this->config->getString('build/path/schema') . "/schema.xml";	
			}
			
			$xsl_file = $this->config->getString('appCoreRootDir') . "/src/main/resources/dbd2propel.xsl";
			
			// Create new XSLTProcessor
			$xslt = new XSLTProcessor();
			
			// Load the XSLT stylesheet
			$xsl = new DOMDocument();
			$xsl->load($xsl_file);
			
			// Load the stylesheet into the processor
			$xslt->importStylesheet($xsl);
			
			// Load XML input file
			$xml = new DOMDocument();
			$xml->load($dbd2_file);
			
			// Transform to a file
			$results = $xslt->transformToURI($xml, $propel_file);
		}

	}
}
?>